package xyz.cerberu.cet.spider.anime.spider.Logic;

import com.spider.core.ProcessLogic;
import com.spider.page.HtmlPage;
import com.spider.page.ResultPage;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author β世界
 * Created on 14:41
 * @Description 分页添加逻辑
 */
@Component
public class HomeLogic implements ProcessLogic {
    /** 分页xpath **/
    private static final String PAGE_XPATH = "//*[@id=\"columnSubjectBrowserA\"]/div[2]/div/div/a[@class=\"p\"]";
    /** 动漫详细页xpath **/
    private static final String ANIME_XPATH = "//ul[@id=\"browserItemList\"]/li/a";

    @Override
    public boolean isProcess(ResultPage resultPage) {
        HtmlPage page = (HtmlPage) resultPage;
        // 检查分页是否存在
        if(page.xpath(PAGE_XPATH).size() != 0) {return true;}
        // 判断是否存在动漫页面
        if(page.xpath(ANIME_XPATH).size() != 0) {return true;}
        return false;
    }

    @Override
    public void logic(ResultPage resultPage) {
        HtmlPage page = (HtmlPage)resultPage;
        String url = page.getUrl().toString();
        // 添加动漫页
        List<Element> elements = page.xpath("//ul[@id=\"browserItemList\"]/li/a");
        for (Element item : elements) {
            page.addUntreated(page.insertDomain(item.attr("href")));
        }

        // 获取当前页面的页码信息
        List<Element> pageList = page.xpath("//*[@id=\"columnSubjectBrowserA\"]/div[2]/div/div/a[@class=\"p\"]");
        for (Element item : pageList) {
            if(url.contains("?")){
                url = url.substring(0,url.indexOf("?"));
            }
            page.addUntreated(url + item.attr("href"));
        }

    }
}
